package web

import (
	"fmt"
	"net/http"
	"rentBack/connect"
	"rentBack/samba"
	"strconv"

	"github.com/labstack/echo"
	"github.com/labstack/echo/middleware"
)

func Start() {
	e := echo.New()
	e.Use(middleware.CORSWithConfig(middleware.CORSConfig{
		AllowOrigins: []string{"http://192.168.100.99:3000", "http://192.168.100.99:8080"},
		AllowHeaders: []string{echo.HeaderOrigin, echo.HeaderContentType, echo.HeaderAccept},
	}))
	e.GET("/uid/:uid", getImageByUid)
	// e.GET("/fam/:fam", getPatientsByFam)
	// e.GET("/date/:date", getPatientsByDate)
	e.GET("/img/:img", getImageByAddress)
	e.Logger.Fatal(e.Start(":80"))
}

func getImageByAddress(c echo.Context) error {
	imageNumber := c.Param("img")
	fmt.Println("img id = ", imageNumber)
	imageNumberInt, err := strconv.Atoi(imageNumber)
	if err != nil {
		fmt.Println(err)
	}
	imagePath := connect.FileAddressByNumber(imageNumberInt)
	file := samba.Load(imagePath)
	fmt.Println("getImage", imagePath)
	return c.Blob(http.StatusOK, "application/dicom", file)
}

func getImageByUid(c echo.Context) error {
	fmt.Println("getImageByUid")
	uid := c.Param("uid")
	intUid, err := strconv.Atoi(uid)
	if err != nil {
		fmt.Println(err)
	}
	_, patientFile := connect.GetImages(intUid)
	if len(patientFile.SchemeList) == 0 {
		fmt.Println("reslutString zero")
		fmt.Printf("%+v\n", patientFile)
		return c.JSON(http.StatusOK, "")
	}
	fmt.Printf("%+v\n", patientFile)
	return c.JSON(http.StatusOK, patientFile)
}
